import React, {useRef, useState} from 'react';
import {DeleteOutlined, FormOutlined, InboxOutlined, PoweroffOutlined} from '@ant-design/icons';
import useCommodity from "@/hooks/getCommodity.js";
import {
    Button, DatePicker, Form, Input, InputNumber, Select, Card, message, Upload, Table, Tag, Popconfirm, Modal
} from 'antd';
import {HTTP} from "@/utils/HTTP.js";
import useChannels from "@/hooks/getChannels.js";
import moment from "moment/moment.js";

const {Option} = Select;
const {Dragger} = Upload;
const props = {
    name: 'file', maxCount: 1, multiple: true, action: 'http://127.0.0.1:3031/commodity/upload', onChange(info) {
        const {status} = info.file;
        if (status === 'done') {
            message.success(`${info.file.name}上传成功!`);
        } else if (status === 'error') {
            message.error(`${info.file.name}上传失败!`);
            console.log('error', info.file, info.fileList);
        }
    }, onDrop(e) {
        console.log('Dropped files', e.dataTransfer.files);
    }
};

const Hot = () => {
    // 点击显示对话框
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 拿到表单实例
    const [form] = Form.useForm();
    // 给编辑按钮绑定点击事件
    const onchange = (record) => {
        setIsModalOpen(true)
        form.setFieldsValue(record)

    }
    //  获取商品类型数据
    const {channelsList} = useChannels();
    // 点击删除按钮
    const onDelete = async (record) => {
        const res = await HTTP({
            url: '/commodity/delete',
            method: 'DELETE',
            data: {
                id: record.id
            }
        })
        if (res.code === 102) {
            location.reload()
            message.success('删除成功')
        } else {
            message.error('删除失败')
        }
    }
    // 自定义列名
    const columns = [{
        title: '商品名称', dataIndex: 'title', key: 'title', render: (_, record) => {
            return (<Tag color={"geekblue"}>
                {record.title}
            </Tag>)
        }
    }, {
        title: '商品价格', dataIndex: 'price', key: 'price',
        render: (_, record) => {
            return (<p>
                {record.price}元
            </p>)
        }
    }, {
        title: '商品类型', dataIndex: 'type', key: 'type', render: (_, record) => {
            return (<p>
                {channelsList.map(item => {
                    if (item.id === record.type) {
                        return item.type
                    }
                })}
            </p>)
        }
    }, {
        title: '时间', dataIndex: 'date', key: 'date', render: (_, record) => {
            return (<p>
                {moment(record.date).format('YYYY-MM-DD')}
            </p>)
        }
    }, {
        title: '操作', dataIndex: '', key: 'x', render: (_, record) => {
            return (<div style={{display: 'flex', justifyContent: 'space-around'}}>
                <Button
                    type="primary"
                    onClick={() => onchange(record)}
                    icon={<FormOutlined/>}
                />
                <Popconfirm
                    title="删除该数据"
                    description="你确定要删除该数据吗？"
                    onConfirm={() => onDelete(record)}
                    okText="确定"
                    cancelText="取消"
                >
                    <Button
                        type="primary"
                        icon={<DeleteOutlined/>}
                        danger={true}
                    />
                </Popconfirm>
            </div>)
        },
    },];
    // 提交修改后的数据
    const onSubmitValue = async () => {
        setIsModalOpen(false);
        let data = form.getFieldsValue()
        const res = await HTTP({
            url: '/commodity/update',
            method: 'PATCH',
            data: data
        })
        if (res.code === 101) {
            location.reload()
            message.success("修改成功")
        } else {
            message.error("修改失败")
        }
    }
    // 清空表单
    const FormRef = useRef();
    // 获取商品数据
    const {list} = useCommodity()
    // 点击提交按钮
    const onFinish = async (values) => {
        const res = await HTTP.post('/commodity/create', values);
        if (res.code === 106) {
            message.success('添加成功!');
            FormRef.current.resetFields();
        } else {
            message.error('添加失败!');
        }
    };

    return (<div style={{
        display: 'flex',
    }}>
        <Card
            style={{
                width: '100%', height: 620, flex: 1, overflow: 'auto'
            }}>

            <div>
                <Form
                    ref={FormRef}
                    style={{
                        maxWidth: 600,
                    }}
                    onFinish={onFinish}
                >
                    <Form.Item
                        label="商品名称"
                        name="title"
                        rules={[{
                            required: true, message: '商品名称不能为空!',
                        },]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="商品价格"
                        name="price"
                        rules={[{
                            required: true, message: '商品价格不能为空!',
                        },]}
                    >
                        <InputNumber
                            style={{
                                width: '100%',
                            }}
                        />
                    </Form.Item>

                    <Form.Item
                        label="商品详情"
                        name="detail"
                        rules={[{
                            required: true, message: '商品详情不能为空!',
                        },]}
                    >
                        <Input.TextArea/>
                    </Form.Item>
                    <Form.Item
                        label={"商品图片"}
                        name="uploadPath"
                        rules={[{
                            required: true, message: '商品图片不能为空!',
                        }]}
                    >
                        <Dragger {...props} style={{width: "180px", height: "180px"}}>
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined/>
                            </p>
                            <p>拖拽图片上传</p>
                        </Dragger>
                    </Form.Item>

                    <Form.Item
                        label="商品类型"
                        name="type"
                        rules={[{
                            required: true, message: '商品类型不能为空!',
                        },]}
                    >
                        <Select>
                            {channelsList.map((item) => {
                                return <Option value={item.id} key={item.id}>{item.type}</Option>
                            })}
                        </Select>
                    </Form.Item>


                    <Form.Item
                        label="选择时间"
                        name="date"
                        rules={[{
                            required: true, message: '时间不能为空!',
                        },]}
                    >

                        <DatePicker style={{width: '300px'}}/>
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 4, span: 16,
                        }}
                    >
                        <Button type="primary" htmlType="submit" style={{width: '200px'}}>
                            提交
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </Card>
        <Card
            title={<div style={{display: "flex", justifyContent: "space-between", alignItems: "center"}}>
                <p>商品数据表</p>
                <Button type={"dashed"} onClick={() => {
                    location.reload()
                }}>刷新</Button>
            </div>}
            style={{flex: 1.5, height: 620, marginLeft: 5}}
        >
            <Table
                rowKey={(record) => record.id}
                columns={columns}
                scroll={{y: 400, x: 300}}
                pagination={{
                    pageSize: 5,
                }}
                expandable={{
                    expandedRowRender: (record, index) => (<div>
                            <p>
                                <i>商品详情：</i>
                                {record.detail}
                            </p>
                            <p>
                                <i>商品图片：</i>
                                <img style={{width: '100px', height: '100px'}}
                                     src={`http://127.0.0.1:3031/${record.uploadPath}`} alt={"商品图片"}/>
                            </p>
                        </div>

                    )
                }}
                dataSource={list}
            />
            <Modal okText={"提交"} cancelText={"返回"} title="编辑商品信息" open={isModalOpen} onOk={onSubmitValue}
                   onCancel={() => {
                       setIsModalOpen(false);
                   }}>
                <div>
                    <Form
                        name="basic"
                        labelCol={{
                            span: 8,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        style={{
                            width: 400,
                        }}
                        form={form}
                    >
                        <Form.Item
                            label={"用户ID"}
                            name="id"
                        >
                            <Input disabled={true}/>
                        </Form.Item>
                        <Form.Item
                            label="商品名称"
                            name="title"
                            rules={[
                                {
                                    required: true,
                                    message: '商品名称不能为空!',
                                },
                            ]}
                        >
                            <Input/>
                        </Form.Item>

                        <Form.Item
                            label="商品价格"
                            name="price"
                            rules={[
                                {
                                    required: true,
                                    message: '商品价格不能为空!',
                                },
                            ]}
                        >
                            <InputNumber/>
                        </Form.Item>
                        <Form.Item
                            label="商品详情"
                            name="detail"
                            rules={[
                                {
                                    required: true,
                                    message: '商品详情不能为空!',
                                },
                            ]}
                        >
                            <Input.TextArea autoSize={{minRows: 3, maxRows: 5}}/>
                        </Form.Item>
                        <Form.Item
                            label="商品类型"
                            name="type"
                            rules={[{
                                required: true, message: '时间不能为空!',
                            },]}
                        >

                            <Select>
                                {channelsList.map((item) => {
                                    return <Option value={item.id} key={item.id}>{item.type}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Form>
                </div>
            </Modal>
        </Card>
    </div>)
};
export default Hot;